/**
 * 生成验证码的辅助类
 */
package com.jeedroid.verifyNumAction;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
public class RandomNumUtil
{
private ByteArrayInputStream image;//图像
private String str="";	//验证码
private RandomNumUtil()
{
	init();
}
public static RandomNumUtil instance()
{
	return new RandomNumUtil();
}
/**
 * 取得验证码图片
 */
public ByteArrayInputStream getImage()
{
	return image;
}
/**
 * 取得图片的验证码
 */
public String getStr()
{
	return str;
}

private void init()
{
	String str_src="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	int width=80,height=20;
	BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	Random random=new Random();
	Graphics g=img.getGraphics();
	//设置背景
	g.setColor(this.getRandomColor(200, 250));
	g.fillRect(0, 0, width, height);
	g.setFont(new Font("Times New Roman",Font.PLAIN,18));
	//随机干扰杂点
			g.setColor(this.getRandomColor(100,200));
			for(int i=0;i<100;i++)
			{
				int x=random.nextInt(width);
				int y=random.nextInt(height);
				g.drawLine(x, y, x-1, y-1);
			}
			//产生验证码
			StringBuilder verifycode=new StringBuilder();
			for(int i=0;i<4;i++)
			{
				verifycode.append(str_src.charAt(random.nextInt(36)));
			}
			g.setColor(this.getRandomColor(0, 255));
			g.drawString(verifycode.toString(), 10, 15);
			this.str=verifycode.toString();
			g.dispose();
			ByteArrayInputStream input=null;
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			try {
				ImageOutputStream imageOut=ImageIO.createImageOutputStream(output);
				ImageIO.write(img, "JPEG", imageOut);
				imageOut.close();
				input = new ByteArrayInputStream(output.toByteArray());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			this.image=input;
}

private Color getRandomColor(int fc, int bc)
{
	Random random=new Random();
	if(fc>255) fc=255;
	if(bc>255) bc=255;
	int r=fc+random.nextInt(bc-fc);
	int g=fc+random.nextInt(bc-fc);
	int b=fc+random.nextInt(bc-fc);
	return new Color(r, g, b);
}
}
